<?php

namespace App\Admin\Forms\Shop;

use App\Models\Shop\WxShop;
use App\Models\Shop\WxShopGuaranteeRecord;
use App\Models\System\AdminUser;
use App\Models\System\RoleUser;
use App\Models\User\WxUser;
use App\Wen\Utils\UserUtils;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Models\Role;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;

class ShopGuaranteeForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * 处理表单请求.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {

        $id = $input['id'];
        $num = _empty_default_($input['num'], 0);
        $title = _empty_default_($input['title'], '');

        if(_empty_($id)){
            return $this->response()
                ->error('参数错误.');
        }

        if(_empty_($num) || _empty_($title)){
            return $this->response()
                ->error('参数错误.');
        }

        $shop = WxShop::find($id);
        if(_empty_($shop)){
            return $this->response()
                ->error('店铺不存在错误.');
        }
        if(UserUtils::update_user_shop_gurantee($shop->user_id, $num, $title)){
            return $this->response()
                ->success('操作成功.')
                ->refresh();
        }else{
            return $this->response()
                ->error('操作失败');
        }
    }

    /**
     * 构建表单.
     */
    public function form()
    {
        $this->hidden('id')->value($this->payload["id"]);
        $total_num = WxShopGuaranteeRecord::where('shop_id', $this->payload["id"])->sum('num');

        $this->html('当前剩余保证金：￥' . $total_num, '');

        $this->number('num', '增加或扣除')->help('负数为扣除')->default(0);
        $this->text('title', '标题')->help('保证金变更记录可以看的到，也就是说用户能看的到')->default('管理员手动操作');
    }

}
